﻿namespace Trading.IBApi

open System
open System.Timers
open System.IO
open com.ib.client
open System.Reactive.Linq


module TickRecorder =

    let recordRTTicks (client:IBrokerGateway) path duration (contract: Contract) =
        let destination = path + contract.m_symbol + @"_"
                            + String.Format(@"{0:yyyy_MM_dd_HH_mm_ss}_{1}", (DateTime.Now.ToLocalTime()), duration)
                            + @".txt"

        use writer = File.CreateText(destination)

        let onNewBar (rtBar: RealTimeBar) =
            printfn "New bar arrived"
            fprintfn writer "%A" rtBar
            
        let bars = client.RealTimeBars(contract, "TRADES") //|> Observable.subscribe (onNewBar)
        let timer = Observable.Timer(TimeSpan.FromSeconds(float duration))

        bars.TakeUntil(timer).ForEach(onNewBar)
